import groovy.transform.Field

/**
 * groovy变量语法
 * def val             val为本地域：脚本内的代码块
 * String val          val为本地域：脚本内的代码块
 * val                 val为绑定域：脚本内的全局作用域
 * @Field String val   val为绑定域：脚本内的全局作用域。加上 @Field 使变量变为绑定域
 * @Field def val      val为绑定域：脚本内的全局作用域。加上 @Field 使变量变为绑定域
 */
// 克隆pipeline脚本到此目录
@Field String pipelineCicdDir = "/usr/local/pipeline_cicd_dir"
// 应用的绝对路径
@Field String applicationRootAbsolute = ""
// 应用的cicd.yaml数据
@Field Map cicdYamlData = [
    notice: [
        wx: [
            key: "",
            ciSuccessSend: false,
            cdSuccessSend: false,
            cdSuccessSend: false,
            cdFailureSend: false
        ]
    ],
    envData: [
        envName : "",
        k8sDeployArgument: [:]
    ]
]

// harbor仓库地址
@Field String insecureRegistry = "192.168.1.239"


/**
 * 字符串是否为空
 * @param str 字符串
 * @return 是否为空
 */
def stringIsBlank(str) {
  str == null || "" == str.trim()
}
/**
 * 获取应用根目录绝对路径
 * @param params Job参数APPLICATION_ROOT_DIR
 * @return 应用根目录绝对路径
 */
def getApplicationRootAbsolute(appRootDir) {
  println "【信息】appRootDir=${appRootDir}"
  return appRootDir ? pwd() + "/" + appRootDir : pwd()
}

/**
 * 需要去Available下安装 pipeline utility steps
 *
 * 读取 cicd/cicd.yaml 数据并返回
 * @param envOption Job参数ENV_OPTION
 * @return Map
 */
def readCicdYaml(String envOption, String appRootAbs) {
  println "【信息】envOption=${envOption}，appRootAbs=${appRootAbs}"
  def yamlData = readYaml file: "${appRootAbs}/cicd/cicd.yaml"
  if (yamlData == "") {
    throw new RuntimeException("【错误】cicd/cicd.yaml的结果为空")
  }

  if (!stringIsBlank(envOption)) {
    String[] envOptionArr = envOption.split('-')
    def envName = envOptionArr[0]
    yamlData.envData = envName == "dev" ? yamlData.dev
        : envName == "test" ? yamlData.test
        : envName == "uat" ? yamlData.uat
        : envName == "prod" ? yamlData.prod
        : cicdYamlData.envData

    // 避免cicd.yaml未配置环境参数
    if (!yamlData.envData) {
      yamlData.envData = cicdYamlData.envData
    }
    yamlData.envData.envName = envName
    println "【信息】yamlData.envData=${yamlData.envData}"

    if (envOptionArr.length >= 2) {
      yamlData.envData.ipArr = envOptionArr[1].split(',')

      println "【信息】yamlData.envData.ipArr=${yamlData.envData.ipArr}"
    }
  }

  // 没有配置 notice ，则设置默认参数避免空指针异常
  if (!yamlData.notice) {
    yamlData.notice = cicdYamlData.notice
  }

  println "【信息】cicd/cicd.yaml读取结果=${yamlData}"
  return yamlData
}

def curlWx(key, applicationName, envName, isSuccess) {
  println "【信息】发送企业微信消息"
  def url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=" + key
  def title = isSuccess ? "成功" : "<font color='warning'>失败</font>"
  sh """
    curl --location --request POST '${url}' \\
    --header 'Content-Type: application/json' \\
    --data '{
        "msgtype": "markdown",
        "markdown": {
            "content": "${title} \\n流水线名称：${applicationName} \\n环境：${envName}"
        }
    }'
  """
}

return this

